package pl.edu.agh.mguesser.ui.main;

import com.google.common.io.Resources;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.swing.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import pl.edu.agh.mguesser.exception.MusicGuesserRuntimeException;
import pl.edu.agh.mguesser.ui.Window;
import pl.edu.agh.mguesser.ui.swing.ImagePanel;

/**
 * @author keiran
 */
@Controller
public class MainMenu extends JPanel {
    
    @Autowired
    private Window window;
    @Autowired
    private NewGame newGame;
    
    private JButton newGameBtn;
    private JButton loadGameBtn;
    private JButton settingsBtn;
    private JButton exitBtn;
    
    @PostConstruct
    public void postConstruct() {
        setLayout(new BorderLayout());
        
        drawLogo();
        addBottomButtons();
        
        bindBottomButtons();
    }

    private void drawLogo() {
        try {
            BufferedImage image = ImageIO.read(Resources.getResource("img/logo.jpg"));
            
            JPanel panel = new ImagePanel(image);
            add(panel, BorderLayout.CENTER);
            
        } catch(IOException ex) {
            throw new MusicGuesserRuntimeException(ex);
            
        }
    }

    private void addBottomButtons() {
        JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        
        newGameBtn = new JButton("New Game");
        buttonsPanel.add(newGameBtn);
        
        loadGameBtn = new JButton("Load Game");
        loadGameBtn.setEnabled(false);
        buttonsPanel.add(loadGameBtn);
        
        settingsBtn = new JButton("Settings");
        settingsBtn.setEnabled(false);
        buttonsPanel.add(settingsBtn);
        
        exitBtn = new JButton("Exit");
        buttonsPanel.add(exitBtn);
        
        add(buttonsPanel, BorderLayout.SOUTH);
    }

    private void bindBottomButtons() {
        newGameBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                window.changePanel(newGame);
            }
        });
        
        exitBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                window.dispose();
            }
        });
    }
    
}
